package com.example.mardan.presenter;

import android.content.Context;
import android.util.Log;

import com.example.mardan.contract.BookContract;
import com.example.mardan.entity.BookEntity;
import com.example.mardan.service.BookService;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class BookPresenter implements BookContract.BookPresenter{
    private static final String TAG = "BookPresenter";
    private static final String BASE_URL = "http://apis.juhe.cn/goodbook/";
    private static final String API_KEY = "02759a01e0ccbeaae0526556634db600";
    private static final int API_PN = 1 ;
    private static final int API_RN = 30 ;
    private static final String API_DTYPE = "json" ;
    private BookContract.BookView view ;
    private Context context ;

    public BookPresenter(BookContract.BookView view, Context context) {
        this.view = view;
        this.context = context;
    }

    @Override
    public void getData(int type) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build() ;

        BookService service = retrofit.create(BookService.class);
        service.getBooks(API_KEY,type,API_PN,API_RN,API_DTYPE)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer<BookEntity>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        view.Loading(true);
                    }

                    @Override
                    public void onNext(@NonNull BookEntity bookEntity) {
                        if (bookEntity != null){
                            view.showData(bookEntity);
                        }else {
                            Log.e("空指针警告", "mMainView 为 null" );
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        Log.e("错误处理", "数据获取失败: " + e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        view.Loading(false);
                    }
                }) ;
    }
}
